package com.example.tcp.server.example;

import com.example.tcp.server.DecoderFactory;
import com.example.tcp.server.Frame;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConditionalOnProperty(prefix = "decoders.example", name = {"enable"}, havingValue = "true")
public class ExampleDecoder implements DecoderFactory.Decoder {
    @Override
    public String id() {
        return "example";
    }

    @Override
    public boolean accept(ChannelHandlerContext ctx, ByteBuf in) {
        return in.readableBytes() >= 2 && in.getUnsignedShort(0) == 0x5555;
    }

    @Override
    public int length(ChannelHandlerContext ctx, ByteBuf in) {
        if(in.readableBytes() >= 4 && in.readableBytes() >= in.getUnsignedShort(2)) {
            int length = in.getUnsignedShort(2);
            if(length >= 4096) { // 最大报文长度不能超过这个值,否则为非法报文
                return -1;
            }
            return length;
        }
        return 0;
    }

    @Override
    public Frame createFrame(ChannelHandlerContext ctx, ByteBuf buf) {
        return new ExampleFrame(buf);
    }

}
